package org.algorithm.二师兄.链表;

import org.algorithm.common.ListNode;

/***
 *  双链表是否是环形
 */
public class 环形链表2 {

    public static void main(String[] args) {
        ListNode node1 = ListNode.build(1,2,3,4);

        ListNode node2 = ListNode.build(0,8);

        ListNode node3 = ListNode.build(5,6,7);

        node1.next = node3;
        node2.next = node3;

        ListNode.print(hasCircle(node1, node2));

    }

    /***
     *  两条链接是否有环
     */
    private static ListNode hasCircle(ListNode node1, ListNode node2) {
        ListNode slow = node1;
        ListNode fast = node2;
        while (slow != fast) {
            slow = slow == null ? node2 : slow.next;
            fast = fast == null ? node1 : fast.next;
        }
        return slow;
    }
}
